﻿
//我的信息
app.controller('MyController', ['$scope', '$http', function ($scope, $http) {
    $http.post('/Information/MyInfor')
        .success(function (resp) {
            $scope.myinfo = resp;
            console.log($scope.myinfo);
        });
}]);
//地址管理
app.controller('AddressController', ['$scope', '$location', '$window', 'AddressService', 'GetSendAddFromMerIdService', function ($scope, $location, $window, AddressService, GetSendAddFromMerIdService) {
    $scope.addressInfo = {
        ID: '',
        ContactName: '',//姓名
        ContactCall: '',//电话
        ContactAddress: '',//地址
        ContactPostal: ''//邮编
    };
    $scope.addresses = [];//地址数组


    //获取地址列表

    //截取url数据方法
    var getParam = function (name) {
        var search = document.location.search;
        //alert(search);
        var pattern = new RegExp("[?&]" + name + "\=([^&]+)", "g");
        var matcher = pattern.exec(search);
        var items = null;
        if (null != matcher) {
            try {
                items = decodeURIComponent(decodeURIComponent(matcher[1]));
            } catch (e) {
                try {
                    items = decodeURIComponent(matcher[1]);
                } catch (e) {
                    items = matcher[1];
                }
            }
        }
        return items;
    };
        //var a = getParam('shopnumber');
        //alert(a);
    var postData = {
        MerId: getParam('shopnumber') === null ? "" : getParam('shopnumber')
    }
    console.log(postData);
    AddressService.list(postData)
        .success(function (resp) {
            console.log(resp);
            $scope.addresses = resp.rows;

        })
        .error(function (resp) { console.log(resp) });

    //获取地址ID，打开修改地址界面
    $scope.updateContact = function (u) {
        //截取url数据方法
        var getParam = function (name) {
            var search = document.location.search;
            //alert(search);
            var pattern = new RegExp("[?&]" + name + "\=([^&]+)", "g");
            var matcher = pattern.exec(search);
            var items = null;
            if (null != matcher) {
                try {
                    items = decodeURIComponent(decodeURIComponent(matcher[1]));
                } catch (e) {
                    try {
                        items = decodeURIComponent(matcher[1]);
                    } catch (e) {
                        items = matcher[1];
                    }
                }
            }
            return items;
        };
        //var a = getParam('shopnumber');
        //alert(a);
        $window.location.href = "/Information/AddAddressV?ContactID=" + u + "&shopnumber=" + getParam('shopnumber');
    }

    //商户派送范围数组
    $scope.merrange = [];
    //根据商户id获取改商户下的所有派送范围
    GetSendAddFromMerIdService.list()
        .success(function (resp) {
            $scope.merrange = resp.list;
            console.log('$scope.merrange', $scope.merrange);
        })
        .error(function (resp) { console.log(resp) });

    //删除地址
    $scope.delContact = function (u) {
        $scope.addressInfo.ID = u;
        console.log(u)

        var json = {
            ID:u
        }

        var postdata_deladdress = {
            json: JSON.stringify(json),
            tag:3
        }
        AddressService.add_edit_del(postdata_deladdress)
            .success(function (resp) {
                //$scope.addresses = resp.rows;
                window.location.reload();//刷新当前页面
            })
            .error(function (resp) {
                console.log(resp);
            });
    }

    $scope.selectA = function (add) {
        //alert(addid);
        
        //document.cookie = "select_address=" + JSON.stringify(add);
        //alert(document.cookie);

        //截取url数据方法
        var getParam = function (name) {
            var search = document.location.search;
            //alert(search);
            var pattern = new RegExp("[?&]" + name + "\=([^&]+)", "g");
            var matcher = pattern.exec(search);
            var items = null;
            if (null != matcher) {
                try {
                    items = decodeURIComponent(decodeURIComponent(matcher[1]));
                } catch (e) {
                    try {
                        items = decodeURIComponent(matcher[1]);
                    } catch (e) {
                        items = matcher[1];
                    }
                }
            }
            return items;
        };
        //var a = getParam('shopnumber');
        //alert(a);

        $window.location.href = "/Order/Index?shopnumber=" + getParam('shopnumber')+"&selectAddress=" + JSON.stringify(add)+"&ContactID=" + add.ID;
    }
}]);
//新增、更新地址
app.controller('UpdateAddressController', ['$scope', '$location', '$window', 'AddressService', 'AllRangeService', 'ChangeAddService', function ($scope, $location, $window, AddressService, AllRangeService, ChangeAddService) {
    //派送范围
    $("#range").hide();
    $scope.MerAddId = {
        AddId: '',
        AddName: '',
        AddStat: ''
    };

    $scope.addressInfo = {
        ID: '',
        ContactName: '',//姓名
        ContactCall: '',//电话
        ContactAddress: '',//地址
        ContactPostal: 000000,//邮编
        MerAddId: '' //派送范围
    };
    $scope.addresses = [];//地址数组
    //获取URL参数，即：获取商户ID。此做法死板，最好能用search()但未能实现
    $scope.addressInfo.ID = $location.absUrl().substring($location.absUrl().lastIndexOf("=") + 1);


    //截取url数据方法
    var getParam = function (name) {
        var search = document.location.search;
        //alert(search);
        var pattern = new RegExp("[?&]" + name + "\=([^&]+)", "g");
        var matcher = pattern.exec(search);
        var items = null;
        if (null != matcher) {
            try {
                items = decodeURIComponent(decodeURIComponent(matcher[1]));
            } catch (e) {
                try {
                    items = decodeURIComponent(matcher[1]);
                } catch (e) {
                    items = matcher[1];
                }
            }
        }
        return items;
    };
        //var a = getParam('shopnumber');
        //alert(a);

    if (getParam('shopnumber') == "null") {
        //获取所有送餐范围
        AllRangeService.list_all()
            .success(function (resp) {
                $scope.MerAddId = resp.rows;
                console.log($scope.MerAddId);
            })
            .error(function (resp) {
                console.log(resp)
            });
    } else {
        var postdata = {
            merid: getParam('shopnumber')
        }
        AllRangeService.list(postdata)
            .success(function (resp) {
                $scope.MerAddId = resp.rows;
                console.log($scope.MerAddId);
            })
            .error(function (resp) {
                console.log(resp)
            });
       
    }

    if ($scope.addressInfo.ID != "") {
        //获取地址列表
        AddressService.list()
            .success(function (resp) {
                $scope.addresses = resp.rows;
                for (var i in $scope.addresses) {
                    if ($scope.addresses[i].ID == $scope.addressInfo.ID) {
                        $scope.addressInfo.ContactName = $scope.addresses[i].ContactName;
                        $scope.addressInfo.ContactCall = $scope.addresses[i].ContactCall;
                        $scope.addressInfo.ContactAddress = $scope.addresses[i].ContactAddress;
                        $scope.addressInfo.ContactPostal = $scope.addresses[i].ContactPostal;
                    }
                }
            })
            .error(function (resp) { console.log(resp) });
    }

    


    

    //选择派送范围
    $scope.changeadd = function (u) {
        ChangeAddService.list($scope.addressInfo)
         .success(function (resp) {
             for (var i in resp.rows) {
                 if (resp.rows[i].MerSendAddId == u) {
                     $scope.addressInfo.ContactAddress = resp.rows[i].AddName;
                 }
             }
             $scope.MerForAdd = resp.rows;
             $("#range").show(1000);
         })
            .error(function (resp) {
                console.log(resp)
            });
    }
    //配送范围的商户集合
    $scope.MerForAdd = {
        AddName: '',
        Id: '',
        MerName: ''
    }

    //新增、修改地址
    $scope.updateContact = function (u) {
        //截取url数据方法
        var getParam = function (name) {
            var search = document.location.search;
            //alert(search);
            var pattern = new RegExp("[?&]" + name + "\=([^&]+)", "g");
            var matcher = pattern.exec(search);
            var items = null;
            if (null != matcher) {
                try {
                    items = decodeURIComponent(decodeURIComponent(matcher[1]));
                } catch (e) {
                    try {
                        items = decodeURIComponent(matcher[1]);
                    } catch (e) {
                        items = matcher[1];
                    }
                }
            }
            return items;
        };
        //var a = getParam('shopnumber');
        //alert(a);

        var json = {
            "ID": 0,
            "AddId": u.MerAddId,
            "Name": u.ContactName,
            "AddrContent": u.ContactAddress,
            "TelNum": u.ContactCall,
            "OpenId": "",
            "Order_MerSendAdd_T": null
        }
        
        AddressService.getsession()
            .success(function (resp) {
                console.log(resp);
                json.OpenId = resp;
                json.OpenId.substring(-1, (json.OpenId - 1));
                console.log(json.OpenId);
                var postdata = {
                    "json": JSON.stringify(json),
                    tag: null
                }
                postdata.tag = 1;
                console.log(postdata);
                AddressService.add_edit_del(postdata)
                    .success(function (resp) {
                        if (resp.BS == "1") {
                            if (getParam('shopnumber')!="null") {
                                $window.location.href = "/Order/Index?isAdd=1&shopnumber=" + getParam('shopnumber') + "&ContactID=";
                            } else {
                                $window.location.href = "/Information/Address";
                            }
                            
                        } else {
                            $scope.alert = 1;
                            $scope.errorMsg = resp;
                        }
                    })
                    .error(function (resp) {
                        console.log(resp)
                    });
            })
            .error(function (resp) {
                console.log(resp);
            });

        
        //if (u.ID == "") {
        //    新增
        //    AddressService.add(u)
        //    .success(function (resp) {
        //        if (resp == "1") {
        //            $window.location.href = "/Information/Address";
        //        } else {
        //            $scope.alert = 1;
        //            $scope.errorMsg = resp;
        //        }
        //    })
        //    .error(function (resp) {
        //        console.log(resp)
        //    });
            

        //} else {
        //    //修改
        //    AddressService.update(u)
        //        .success(function (resp) {
        //            if (resp == "1") {
        //                $window.location.href = "/Information/Address";
        //            } else {
        //                console.log(resp)
        //            }
        //        })
        //        .error(function (resp) {
        //            console.log(resp)
        //        });
        //}
       
            

        
    }

}]);
//我的账户管理
app.controller('AccountInformationController', ['$scope', 'UserAccountService', function ($scope, UserAccountService) {
    $("#spinner").hide();//正在加载字样隐藏
    //alert(true);
    $scope.allUserWalt = [];
    $scope.UserWalt = {
        waltname: '',
        waltbalance: ''
    };
    $("#waltDetail").hide();//隐藏流水表
    console.log("开始");
    var d = new Date();
    console.log("1 " + d.toLocaleDateString());
    UserAccountService.balance()
        .success(function (resp) {
            $scope.allUserWalt = resp.rows;
        })
        .error(function (resp) { console.log(resp) });

    $scope.showdetail = 0;
    var index = 1;
    $scope.showDetailTable = function (data, accnum, waltid) {
        console.log("data:" + data + "," + "accid:" + accnum + "," + "waltid:" + waltid);
        console.log("2 " + d.getSeconds());
        if (data == 0) {
            $scope.showdetail = 1;
            $("#waltDetail").show();
            $("#showdetail" + waltid + "").text("收起流水");
            function lowEnough() {
                var pageHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight);
                var viewportHeight = window.innerHeight ||
                        document.documentElement.clientHeight ||
                        document.body.clientHeight || 0;
                var scrollHeight = window.pageYOffset ||
                        document.documentElement.scrollTop ||
                        document.body.scrollTop || 0;
                return pageHeight - viewportHeight - scrollHeight < 20;
            }
            console.log("收取流水");
            console.log("3 " + d.getSeconds());
            function doSomething() {
                var postData = {
                    AccNum: accnum,

                    WaltID: waltid,
                    pageIndex: index,
                    pageSize: 10
                }

                console.log("页码：" + postData.pageIndex);
                //获取流水表
                UserAccountService.water(postData).success(function (resp) {
                    if (resp != "查询不到数据") {
                        console.log("4 " + d.getSeconds());
                        var result = resp.rows;
                        if (result.length > 0) {
                            var htmlStr = "";
                            for (var i = 0; i < result.length; i++) {
                                htmlStr += "<div class='more_style'><div class='time_left'><div class='type'>" + result[i].WaltFlowTypeName
                                    + "</div><div class='time'>" + result[i].WaltFlowTime + "</div></div><div class='mon'><div class='less_mon'>￥" + result[i].WaltHaveNub
                                    + "</div><div class='rest_mon'><span>余</span><span>￥" + result[i].WaltEndNub + "</span></div></div><div class='cls'></div></div>"
                            }
                            $('#waltDetail').append(htmlStr);
                            index++;
                            pollScroll();//继续循环
                            $('#spinner').hide();//正在加载字样隐藏
                            console.log("5 " + d.getSeconds());
                        } else {

                            htmlStr = "<div class='more_style'>没有更多了~</div>";
                            $('#waltDetail').append(htmlStr);
                            $('#spinner').hide();//正在加载字样隐藏

                        }
                    }
                    else {
                        htmlStr = "<div class='more_style'>没有数据~</div>";
                        $('#waltDetail').append(htmlStr);
                        $('#spinner').hide();//正在加载字样隐藏
                    }
                }).error(function (resp) {
                    console.log("错误！");
                    console.log(resp);
                });
            }

            function checkScroll() {
                if (!lowEnough()) return pollScroll();
                $('#spinner').show();//正在加载字样显示
                setTimeout(doSomething, 900);
                console.log("dosomething");

            }
            function pollScroll() {
                setTimeout(checkScroll, 1000);
            }
            checkScroll();

        } else {
            console.log("6 " + d.toLocaleDateString);
            index = 1;
            $scope.showdetail = 0;
            $("#waltDetail").html(""); //收起明细之后清除明细内容
            $("#showdetail" + waltid + "").text("查看流水");
        }
    };
}])
// 我的积分
app.controller('IntegralController', ['$scope', '$http', 'UserIntService', function ($scope, $http, UserIntService) {
    $scope.myIntList = [];
    $scope.PlatformInt = '';
    $scope.MerInt = [];

    console.log(1);
    UserIntService.userint()
        .success(function (resp) {
            $scope.myIntList = resp.rows;
            //console.log($scope.myIntList);
            for (var i in $scope.myIntList) {
                if ($scope.myIntList[i].MerID == 0) {
                    $scope.PlatformInt = $scope.myIntList[i];
                } else {
                    $scope.MerInt.push($scope.myIntList[i]);
                }
            }
            console.log($scope.PlatformInt);
            console.log($scope.MerInt);
        })
        .error(function (resp) { console.log(resp) });
}]);

//选择派送范围显示商户
app.factory('ChangeAddService', ['$http', function ($http) {
    var list = function (postdata) {
        console.log('post', postdata);
        return $http.post('/Information/getmerfromadd', postdata);
    }
    return {
        list: function (u) {
            return list(u);
        }
    };
}]);

app.factory('GetSendAddFromMerIdService', ['$http', function ($http) {
    //根据商户id获取该商户下的所有派送范围
    var list = function () {
        return $http.post('/Information/getallsendfrommerid');
    }
    return {
        list: function () {
            return list();
        }
    };
}]);
app.factory('AddressService', ['$http', function ($http) {
    //获取地址列表
    //var list = function () {
    //    return $http.post('/Information/getAddress');
    //}
    var list = function (postdata) {
        return $http.post('/Information/GetUserSendAddr', postdata);
    }
    //新增新地址
    var add = function (postdata) {
        console.log('新增地址', postdata);
        return $http.post('/Information/addNewAddress', postdata);
    }
    //修改地址
    var upadte = function (postdata) {
        console.log('修改地址', postdata);
        return $http.post('/Information/updateAddress', postdata);
    }
    //删除地址
    var del = function (postdata) {
        //console.log(ID);
        return $http.post('/Information/delAddress', postdata);
    }
    //新的增删改地址
    var add_edit_del = function (postdata) {
        //console.log(ID);
        return $http.post('/Information/SetUserSendAddr', postdata);
    }

    //获取session中appid
    var getsession = function () {
        //console.log(ID);
        return $http.post('/Information/GetSession');
    }

    return {
        list: function (postdata) { return list(postdata); },
        add: function (u) { return add(u) },
        update: function (postdata) { return upadte(postdata) },
        del: function (contactid) { return del(contactid) },
        add_edit_del: function (u) { return add_edit_del(u) },
        getsession: function () { return getsession() }
    }
}]);
app.factory('AllRangeService', ['$http', function ($http) {
    //获取所有派送范围
    var list_all = function () {
        console.log("派送范围");
        return $http.post('/Information/GetAllAddByUser');
    }
    //获取派送范围 新
    var list = function (postdata) {
        console.log("派送范围");
        return $http.post('/Information/GetSendAddFromMerId',postdata);
    }
    return {
        list_all: function () {
            return list_all();
        },
        list: function (postdata) {
            return list(postdata);
        }
    };
}]);
app.factory('UserAccountService', ['$http', function ($http) {
    //获取钱包余额
    var balance = function () {
        return $http.post('/Information/getWaltBalance');
    }
    //获取消费流水
    var water = function (postData) {
        return $http.post('/Information/getWaltWater', postData);
    }
    return {
        balance: function () {
            return balance()
        },
        water: function (postData) {
            return water(postData)
        }
    }
}]);
app.factory('UserIntService', ['$http', function ($http) {
    var userint = function () {
        return $http.post('/Information/getUserInt');
    }

    return {
        userint: function () { return userint() }
    }
}]);